using System.Collections.Generic;
using NodeCanvas.Variables;
using UnityEngine;

namespace NodeCanvas.BehaviourTrees
{
	[AddComponentMenu("")]
	[Name("Probability Selector")]
	[Category("Composites")]
	[Description("Select a child to execute based on it's chance to be selected and return Success if it returns Success, otherwise pick another.\nReturns Failure if no child returns Success or a direct 'Failure Chance' is introduced")]
	[Icon("ProbabilitySelector")]
	public class BTProbabilitySelector : BTComposite
	{
		public List<BBFloat> childWeights = new List<BBFloat>();

		public BBFloat failChance = new BBFloat();

		private float probability;

		private float currentProbability;

		private float total;

		public override string nodeName
		{
			get
			{
				return string.Format("<color=#b3ff7f>{0}</color>", base.nodeName.ToUpper());
			}
		}

		public override void OnPortConnected(int index)
		{
			childWeights.Insert(index, new BBFloat
			{
				value = 1f,
				bb = base.graphBlackboard
			});
			UpdateNodeBBFields(base.graphBlackboard);
		}

		public override void OnPortDisconnected(int index)
		{
			childWeights.RemoveAt(index);
		}

		public override void OnGraphStarted()
		{
			OnReset();
		}

		protected override Status OnExecute(Component agent, Blackboard blackboard)
		{
			currentProbability = probability;
			for (int i = 0; i < base.outConnections.Count; i++)
			{
				if (currentProbability >= childWeights[i].value)
				{
					currentProbability -= childWeights[i].value;
					continue;
				}
				base.status = base.outConnections[i].Execute(agent, blackboard);
				if (base.status == Status.Running || base.status == Status.Success)
				{
					return base.status;
				}
			}
			return Status.Failure;
		}

		protected override void OnReset()
		{
			CalcTotal();
			probability = Random.Range(0f, total);
		}

		private void CalcTotal()
		{
			total = failChance.value;
			foreach (BBFloat childWeight in childWeights)
			{
				total += childWeight.value;
			}
		}
	}
}
